package com.music.mysongs.fragment.option

import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.EditText
import android.widget.ImageView
import androidx.appcompat.app.AlertDialog
import androidx.fragment.app.DialogFragment
import androidx.fragment.app.Fragment
import com.google.gson.Gson
import com.music.mysongs.R
import com.music.mysongs.activity.MainActivity
import com.music.mysongs.data.MusicCreatorData
import com.music.mysongs.data.getApiAccountUpdate
import com.music.mysongs.helper.*
import com.music.mysongs.utils.myGoActivity
import com.music.mysongs.utils.myLog
import com.music.mysongs.utils.myToastWithoutCxt
import com.music.mysongs.web.CommonWebTask
import kotlinx.android.synthetic.main.fragment_account.*

class AccountFragment : Fragment(), View.OnClickListener {
    private val mTAG = "AccountFragment"
    private val codeHEAD = 10
    private val imgHelper = ImgHelper()
    private var headImg: ImageView? = null
    private var editName: EditText? = null
    private var editPsd: EditText? = null
    private var btnPost: Button? = null

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        val name = myActReadStringSPF(this.activity, "spfUserName")
        if (name == "none") {
            myLog("$mTAG: name=$name")
            myGoActivity(requireContext(), MainActivity::class.java)
        } else {
            editName!!.setText(name)
        }
        headImg!!.setOnClickListener(this)
        btnPost_account.setOnClickListener(this)
    }

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.imgUserHead_account -> {
                val fileIntent = Intent(Intent.ACTION_OPEN_DOCUMENT)
                fileIntent.addCategory(Intent.CATEGORY_OPENABLE)
                fileIntent.type = "image/*"
                startActivityForResult(fileIntent, codeHEAD)
            }
            R.id.btnPost_account -> {
                AlertDialog.Builder(requireContext()).apply {
                    setTitle("确定提交？")
                    setPositiveButton("提交") { _, _ ->
                        val mid = myCxtReadIntSPF(context, "spfUserId")
                        val newName = editNewName_account.text.toString()
                        val newPsd = editNewPwd_account.text.toString()
                        if (mid != null) {
                            postAdminData(mid, newName, newPsd)
                        } else {
                            myLog("$mTAG: idSPF null")
                        }
                    }
                    setNegativeButton("取消") { _, _ ->
                        myToastWithoutCxt("名字一年只能改一次哦")
                    }
                    show()
                }
            }
        }
    }

    private fun postAdminData(mid: Int, mName: String, mPsw: String) {
        val musicTask = CommonWebTask()
        musicTask.url = getApiAccountUpdate(mid, mName, mPsw.toInt())
        musicTask.setCallbackHandler { innerData ->
            val data = Gson().fromJson(innerData, MusicCreatorData.MusicNum::class.java)
            if (data.code == 20000) {
                myToastWithoutCxt("修改成功！即将返回主界面")
                myActWriteSPF(this.activity, "spfUserId", null, mid)
                myActWriteSPF(this.activity, "spfUserName", mName, null)
                Handler().postDelayed({
                    myGoActivity(this.requireContext(), MainActivity::class.java)
                }, 1000 * 2.toLong())
            } else {
                myLog(data.data.toString())
            }
        }
        musicTask.execute()
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        when (requestCode) {
            codeHEAD -> {
                if (resultCode == Activity.RESULT_OK && data != null) {
                    data.data?.let { uri ->
                        // 将选择的照片显示
                        val bitmap = imgHelper.getBitmapFromUri(uri)
                        myLog("$mTAG: uri=$uri")
                        if (bitmap != null) {
                            val result = imgHelper.generateScaledBmp(bitmap, 68, 68, 70)
                            imgUserHead_account.setImageBitmap(result)
                        } else {
                            imgUserHead_account.setImageBitmap(bitmap)
                        }
                    }
                }
            }
        }
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        super.onCreateView(inflater, container, savedInstanceState)
        val v = inflater.inflate(R.layout.fragment_account, container, false)
        headImg = v.findViewById(R.id.imgUserHead_account)
        editName = v.findViewById(R.id.editNewName_account)
        editPsd = v.findViewById(R.id.editNewPwd_account)
        btnPost = v.findViewById(R.id.btnPost_account)
        return v
    }
}